---------------------------------------------------
-- 过关斩将/圣树试炼 db

-- 战斗对象
-- drillObj = {_id,lv,head,headFrame,name,unionUuid,zhandouli,svrIndex,heroList,pet}
-- 活动数据（进度等）
-- drillData = {_id,drillId,drillObjs,heroStatus,buff,oper}
---------------------------------------------------

local Config = require("Config")
local DrillExcel = require("excel.drill")
local LuaMongo = _G.lua_mongo
local DB = require("common.DB")
local Util = require("common.Util")
local CommonDB = require("common.CommonDB")
local CombatLogic = require("combat.CombatLogic")
local CombatDefine = require("combat.CombatDefine")
local CreateRole = require("role.CreateRole")
local RoleLogic = require("role.RoleLogic")
local BillboardDefine = require("billboard.BillboardDefine")
local BillboardDB = require("billboard.BillboardDB")
local FieldsRandom = {uuid = 1, zhandouli = 1}
FieldsDot = {drillId = 1, heroStatus = 1}
FieldsHelpInfo = {helpInfo = 1}
QueryByUuid = {_id = nil}
local QueryDrillByRandom = {zhandouli = {["$gte"] = 0, ["$lte"] = 0}, uuid = {["$nin"] = {}}}

MONSTER_OBJLIST = MONSTER_OBJLIST or {} 		-- 

local DRILL_DATA = {}
function isUuidExistInDB(uuid)
	QueryByUuid._id = uuid
	LuaMongo.find(DB.db_drill, QueryByUuid, FieldName)
	return LuaMongo.next(DRILL_DATA) and DRILL_DATA
end


-- (本服)创建玩家对战信息
function createDrillData(human, drillId)
	local heroList, helpList, rolebase , formation, jiban = CombatLogic.getHumanObjList(human, CombatDefine.COMBAT_TYPE1)
	if not heroList or not next(heroList) then return end -- 没有上阵

	local drillData = {}
	drillData._id = human.db._id
	drillData.uuid = human.db._id
	drillData.drillId = drillId 		-- 当前关卡id 1-16,16表示已通关
	drillData.drillObjs = {} 			-- 关卡对象列表[drillId] = drillObj	
	drillData.heroList = heroList
	drillData.helpList = helpList
    drillData.jiban = jiban
	drillData.formation = formation
	drillData.heroStatus = nil			-- 英雄状态 [heroUuid] = hpRate
	drillData.helpUuids = nil 			-- 雇佣的助战英雄
	drillData.buff = nil 				-- 已获得buffer [id] = cnt
	drillData.oper = nil 				-- 操作次数 [optype] = cnt
	drillData.zhandouli = rolebase.zhandouli
	return drillData
end

-- (本服)获取数据
function getDrillDataByUuid(uuid, fields)
	if _G.is_middle then return end		
	if not uuid then return end -- 不能是空哦
	QueryByUuid._id = uuid
    LuaMongo.find(DB.db_drill, QueryByUuid, fields)
    local drillData = {}
	if not LuaMongo.next(drillData) then
		return 
	end
    return drillData.drillId and drillData	
end

-- (本服)更新
function updateDrillData(drillData)
	if _G.is_middle then return end			
	if not drillData._id then return end
	if not drillData.drillId then return end
	local uuid = drillData._id
	if isUuidExistInDB(uuid) then
		QueryByUuid._id = uuid
		LuaMongo.update(DB.db_drill, QueryByUuid, drillData)
	else
		LuaMongo.insert(DB.db_drill, drillData)
	end	
end

-- (本服)检查是否需要重置
function checkDrillReset()
	if _G.is_middle then return end	

	local drill = CommonDB.getValueByKey(CommonDB.KEY_DRILL)
	if not drill or not Util.isSameDay(drill.time) then
		reset()
		drill = {}
		drill.time = os.time()
		CommonDB.updateValue(CommonDB.KEY_DRILL, drill)		
	end
end

-- (本服)创建对象数据（怪物）
function createDrillMonster(uuid, monsterOutID, zhandouli)
	if not uuid then return end
	local heroList, helpList, rolebase, formation = CombatLogic.getMonsterObjList(monsterOutID)
	if not rolebase then return end

	local drillObj = {}
	RoleLogic.makeRoleBase(rolebase, drillObj, true) -- 先初始角色基础信息
	drillObj.uuid = uuid 
	drillObj.svrIndex = 1
	drillObj.svrName = Config.SVR_NAME
	drillObj.heroList = heroList
	drillObj.helpList = helpList
	drillObj.formation = formation
	drillObj.monsterOutID = monsterOutID 			-- 怪物额外字段
	drillObj.objStatus = nil						-- 英雄状态 [index] = hpRate
	
	-- 重新设置某些基础信息
	drillObj.name = CreateRole.getRandomName()
	drillObj.head = CreateRole.getRandomHead()	
	drillObj.zhandouli = zhandouli
	return drillObj
end

-- (本服)每次重启都重新生成怪物数据
local MONSTER_RANDOM_CNT = 15 -- 每个区间生成怪物数量
function createMonsterDrillObj()
	MONSTER_OBJLIST = {}
	for i = 1, #DrillExcel.npc do
		local config = DrillExcel.npc[i]
		for j = 1, MONSTER_RANDOM_CNT do
			local zhandouli = math.random(config.zhandouli[1], config.zhandouli[2])
			local r = math.random(1, #config.monsterOutID)			
			local monsterOutID = config.monsterOutID[r]
			local monsterUuid = "npc-" .. i .. "-" .. j
			local drillObj = createDrillMonster(monsterUuid, monsterOutID, zhandouli)
            MONSTER_OBJLIST[#MONSTER_OBJLIST + 1] = drillObj
		end
	end	
end

-- 创建对象数据（人物）
function createDrillObj(uuid)
	local fakeHuman = CombatLogic.createCombatFakeHuman(uuid)
	if not fakeHuman then return end

	local objList, helpList, rolebase, formation, jiban = CombatLogic.getHumanObjList(fakeHuman, CombatDefine.COMBAT_TYPE1)
	if not objList or not next(objList) then return end -- 没有上阵

	local drillObj = {}
	RoleLogic.makeRoleBase(rolebase, drillObj, true) -- 先初始角色基础信息
	drillObj._id = fakeHuman.db._id 
	drillObj.uuid = nil
	drillObj.heroList = objList
	drillObj.helpList = helpList
	drillObj.formation = formation
	drillObj.jiban = jiban
	drillObj.objStatus = nil						-- 英雄状态 [index] = hpRate
	return drillObj
end

-- (本服)随机一个战斗对象
local RANDOM_LIST = {}
function randomDrillObj(zdlMin, zdlMax, ninTb, isMonster)
	local cnt = 0
	local without = {}
	for _, uuid in pairs(ninTb) do
		without[uuid] = true
	end
	if isMonster then
		RANDOM_LIST = {}
		for _, drillObj in ipairs(MONSTER_OBJLIST) do
			if drillObj.zhandouli >= zdlMin and 
				drillObj.zhandouli <= zdlMax and 
				not without[drillObj.uuid] then
				cnt = cnt + 1
				RANDOM_LIST[cnt]= drillObj
			end
		end
		if cnt < 1 then return end
		local r = math.random(1, cnt)
		return RANDOM_LIST[r]
	else
		RANDOM_LIST = {}
		local board = BillboardDB.getBoard(BillboardDefine.TYPE_ZHANDOULI)
		local boardLen = board and #board.rank2data or 0
		for i = 1, boardLen do
			local rankData = board.rank2data[i]
			if zdlMin <= rankData.value1 and 
				rankData.value1 <= zdlMax and
				not without[rankData.uuid] then
				cnt = cnt + 1
				RANDOM_LIST[cnt] = rankData.uuid
			end
		end
		if cnt < 1 then return end
		local r = math.random(1, cnt)
		local uuid = RANDOM_LIST[r]
		return createDrillObj(uuid)
	end
end

function reset()
	LuaMongo.remove(DB.db_drill)	
	createMonsterDrillObj()	
end

function initAfterStart()
	createMonsterDrillObj()
	checkDrillReset()
end

